public class Solution687 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int max=0;

    public int longestUnivaluePath(TreeNode root) {
        dfs(root);
        return Math.max(0,max-1);
    }

    private int dfs(TreeNode root) {
        if (root==null){
            return 0;
        }
        int x=dfs(root.left);
        int y=dfs(root.right);
        int t=1;
        int tt=1;
        if (x>0 && root.left.val==root.val){
            t+=x;
            tt+=x;
        }
        if (y>0 && root.right.val==root.val){
            t+=y;
            tt=Math.max(tt,1+y);
        }
        max=Math.max(max,t);
        return tt;
    }

    public static void main(String[] args) {
        System.out.println(new Solution687().longestUnivaluePath(new TreeNode(5,new TreeNode(4,new TreeNode(1),new TreeNode(1)),new TreeNode(5,null,new TreeNode(5)))));
    }
}
